package com.drugmanage.service.impl;

import com.drugmanage.Base.BaseService;
import com.drugmanage.dao.ProducerDao;
import com.drugmanage.entity.Producer;
import com.drugmanage.query.ProducerQuery;
import com.drugmanage.service.IProducerService;
import com.drugmanage.utils.AssertUtil;
import com.drugmanage.utils.ValidateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProducerService extends BaseService<Producer> implements IProducerService {

    @Resource
    private ProducerDao producerDao;

    @Override
    public Producer queryById(Integer id) {
        AssertUtil.isTure(ValidateUtil.nullOrZeroInteger(id),"producerid is needed");
        Producer producer = producerDao.get(id);
        AssertUtil.isTure(producer==null,"this producer doesnot exist");
        return producer;
    }

    @Override
    public void insertProducer(Producer producer) {
        checkParam(producer);
        producerDao.save(producer);
    }

    private void checkParam(Producer producer) {
        AssertUtil.isTure(ValidateUtil.blankString(producer.getProducerName()),"producerName is needed");
        AssertUtil.isTure(ValidateUtil.blankString(producer.getLocation()),"location is needed");
        AssertUtil.isTure(ValidateUtil.blankString(producer.getTel()),"telephone is needed");
        producer.setCreateDate(new Date());
        producer.setUpdateDate(new Date());
        producer.setIsValid(true);
    }

    @Override
    public void updateProducer(Producer producer) {
        producerDao.update(producer);
    }

    @Override
    public void deleteById(Integer id) {
        AssertUtil.isTure(ValidateUtil.nullOrZeroInteger(id),"id is needed");
        producerDao.delete(id);
    }

    @Override
    public Map<String, Object> queryForPage(ProducerQuery producerQuery) {
        PageHelper.startPage(producerQuery.getPage(),producerQuery.getRows());
        PageInfo<Producer> pageInfo=new PageInfo<Producer>(producerDao.queryForPage(producerQuery));
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("total", pageInfo.getTotal());
        map.put("rows", pageInfo.getList());
        return map;
    }

    @Override
    public void deleteBatchs(Integer[] ids){
        if(ids!=null&&ids.length>0){
            producerDao.deleteBatch(ids);
        }else {
            AssertUtil.isTure(true,"请选择要删除的记录");
        }
    }
}
